import os
import subprocess
import sys

env = Environment()

py_ver = sys.version[:3]

if not env.GetOption( 'clean' ):
    shs = map( subprocess.Popen, map( str, env.Glob( 'ext/*.sh' ) ) )
    assert all( [ not sh.wait() for sh in shs ] )
    
env.Append( CPPFLAGS = [ '-g', '-Wall', '-Werror' ] )
env.Append( CPPPATH = [ '#', '/usr/include/python%s' % py_ver, 'ext/yaml-cpp/include', 'ext/box2d/include', 'ext/bullet/include/bullet', 'ext/tinyxml', 'ext/gtest/include' ] )
env.Append( LIBPATH = [ 'ext/yaml-cpp/lib', 'ext/box2d/lib', 'ext/bullet/lib', 'ext/gtest/lib' ] )
env.Append( LIBS = [ 'boost_filesystem', 'python%s' % py_ver, 'boost_python', 'ncurses', 'yaml-cpp', 'Box2D', 'BulletCollision', 'BulletDynamics', 'LinearMath' ] )
pwd = env.Dir( '#' ).abspath
env.Append( RPATH = [ pwd, pwd + '/ext/yaml-cpp/lib', pwd + '/ext/bullet/lib', pwd + '/ext/gtest/lib' ] )

tinyxml = env.SharedLibrary( 'ext/tinyxml/tinyxml', env.Glob( 'ext/tinyxml/tiny*.cpp' ) )

env = env.Clone()
env.Append( LIBS = [ tinyxml ] )

mod_libs = []
for mod in filter( os.path.isdir, map( str, env.Glob( 'fhe/*' ) ) ):
   mod_srcs = env.Glob( '%s/*.cpp' % mod )
   mod_libs.append( env.SharedLibrary( mod, mod_srcs ) )
    
env = env.Clone()
env.Append( LIBS = [ mod_libs ] )

env.SharedLibrary( 'fhe', [], SHLIBPREFIX = '' )

apps = map( env.Program, env.Glob( 'apps/*.cpp' ) )

env = env.Clone()
env.Append( LIBS = [ 'gtest' ] )

test_srcs = env.Glob( 'tests/*.cpp' )
for test_src in test_srcs:
    test = env.Program( test_src )
    test_name = str( test[0] )
    env.Command( test_name + '.out', test, test_name )
